<?php
namespace App\Models\Admin;

use App\Basic\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use \Illuminate\Support\Facades\Config as FacadesConfig;

/**
* @comment 供应商配置
*
* @property int $sid
* @property string $private_key 私钥
* @property string $database_link 连接
* @property string $domain 供应商后台地址域名
* @property string $domain_ssl 后台域名https: 1=是,2=不是
*
* @property Supplier $supplier
*/
class SupplierConfiguration extends Model
{

    protected $primaryKey = 'sid';

    /**
     * @var string
     */
    protected $connection = 'admin';

    /**
     * @var string
     */
    protected $table = 'supplier_configuration';

    /**
     * @var string[]
    */
    protected $fillable = ['sid', 'private_key', 'database_link', 'domain'];

    /**
     * @return BelongsTo
     */
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class, 'sid', 'id');
    }

    /**
     * @return void
     */
    public static function registerDbConnectAll(): void
    {
        self::query()
            ->where('database_link', '<>', '')
            ->chunk(200, fn (Collection $collection) => $collection->map(fn (SupplierConfiguration $config) => $config->registerDbConfig()));
    }

    /**
     * @param string $dbKey
     * @return bool|string
     */
    public function registerDbConfig(string $dbKey = ''): bool|string
    {
        if (!$this->database_link) {
            return false;
        }
        $dbKey = $dbKey ?: dbConnectKey($this->sid);
        // 解析link
        $arr = explode(':', $this->database_link);
        if (count($arr) != 5) {
            return false;
        }
        FacadesConfig::set('database.connections.' . $dbKey, [
            'driver'        => 'mysql',
            'host'          => $arr[0],
            'port'          => $arr[1],
            'database'      => $arr[4],
            'username'      => $arr[2],
            'password'      => $arr[3],
            'charset'       => 'utf8mb4',
            'collation'     => 'utf8mb4_unicode_ci',
            'prefix_indexes'=> true,
            'strict'        => false,
            'options'       => extension_loaded('pdo_mysql') ? array_filter([
                \PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]);
        return $dbKey;
    }
}
